import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
// import { match, RouterContext } from 'react-router';
import { BrowserRouter, StaticRouter } from 'react-router-dom';
import { matchRoutes, renderRoutes } from 'react-router-config';
import { AppContainer } from 'react-hot-loader';
import { LocaleProvider } from 'antd';
import zhCN from 'antd/lib/locale-provider/zh_CN';
import Layout from './Layout.jsx';
import { create } from 'store';
import routes from 'router';
import 'asset/styles/normalize.css';
import 'antd/dist/antd.less';
import 'asset/iconfont/iconfont.css';
import 'asset/styles/base.less';

const NotFound = () => {
  return (
    <Route render={({ staticContext }) => {
      if (staticContext) {
        staticContext.status = 404;
      }
      return (
        <div>
          <h1>404 : Not Found</h1>
        </div>
      );
    }}/>
  );
};

const clientRender = () => {
  const store = create(window.__INITIAL_STATE__);
  const Entry = () => (
    <LocaleProvider locale={zhCN}>
      <Provider store={ store }>
        <BrowserRouter>
          {renderRoutes(routes)}
        </BrowserRouter>
      </Provider>
    </LocaleProvider>
  );
  const render = Page => {
    ReactDOM.hydrate(EASY_ENV_IS_DEV ? <AppContainer><Page /></AppContainer> : <Page />, document.getElementById('app'));
  };
  if (EASY_ENV_IS_DEV && module.hot) {
    module.hot.accept();
  }
  render(Entry);
};

const serverRender = (context, options) => {
  const url = context.state.url;
  // const newRoutes = routes.push({
  //   path: '*',
  //   component: NotFound,
  // });
  const branch = matchRoutes(routes, url);
  const promises = branch.map(({ route }) => {
    const fetch = route.component.fetch;
    return fetch instanceof Function ? fetch() : Promise.resolve(null);
  });
  return Promise.all(promises).then(data => {
    const initState = context.state;
    data.forEach(item => {
      Object.assign(initState, item);
    });
    context.state = Object.assign({}, context.state, initState);
    const store = create(initState);
    return () => (
      <LocaleProvider locale={zhCN}>
        <Provider store={store}>
          <Layout>
            <StaticRouter location={url} context={{}}>
              {renderRoutes(routes)}
            </StaticRouter>
          </Layout>
        </Provider>
      </LocaleProvider>
    );
  });
};
export default EASY_ENV_IS_NODE ? serverRender : clientRender();
